//
//  ChooseIMGView.m
//  HCFrame
//
//  Created by 丁 一 on 2018/6/22.
//  Copyright © 2018年 丁 一. All rights reserved.
//

#import "ChooseIMGView.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "XLPhotoBrowser.h"
#import "SGImagePickerController.h"
#import "ChooseIMGCollectionCell.h"

@interface ChooseIMGView ()<UICollectionViewDataSource,UICollectionViewDelegate,UIImagePickerControllerDelegate,UIImagePickerControllerDelegate,UITextViewDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UIButton                    *Choosebutton;

@end

@implementation ChooseIMGView

+(ChooseIMGView *)Show:(CGRect)rect Array:(NSMutableArray *)Array{
    
    ChooseIMGView *img_view=[[ChooseIMGView alloc] initWithFrame:rect andArray:Array];
    return img_view;
}

-(instancetype)initWithFrame:(CGRect)frame andArray:(NSMutableArray *)Array{
    self=[super initWithFrame:frame];
    if (self) {
        
        _Array = Array;
        
        UICollectionViewFlowLayout *fallLayout = [[UICollectionViewFlowLayout alloc] init];
        fallLayout.scrollDirection             = UICollectionViewScrollDirectionHorizontal;
        fallLayout.itemSize                    = CGSizeMake(frame.size.height, frame.size.height);
        fallLayout.minimumInteritemSpacing     = 0;
        fallLayout.minimumLineSpacing          = 0;
        
        _collectionview = [[UICollectionView alloc] initWithFrame:CGRectMake(5, 0,frame.size.width, frame.size.height) collectionViewLayout:fallLayout];
        [_collectionview setDelegate:self];
        [_collectionview setDataSource:self];
        [_collectionview setShowsHorizontalScrollIndicator:NO];
        [_collectionview setShowsVerticalScrollIndicator:NO];
        [_collectionview setBackgroundColor:[UIColor clearColor]];
        [_collectionview registerClass:[ChooseIMGCollectionCell class] forCellWithReuseIdentifier:@"cell"];
        [self addSubview:_collectionview];
        
    }
    return self;
}

-(void)setherearray:(NSMutableArray *)array{
    _Array = array;
    [self here_relaod];
}

-(void)set_img_view:(NSMutableDictionary *)img_dic{
    [_Array addObject:img_dic];
    [SVProgressHUD showWithStatus:@"加载图片.."];
    [_collectionview reloadData];
}

#pragma mark-表头尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeZero;
}

#pragma mark---UICollectionViewDelegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    [SVProgressHUD dismiss];
    
    if (_Array.count>2) {
        return _Array.count;
    }else{
        return _Array.count+1;
    }
}

#pragma mark---加载UICollectionViewDataSource
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ChooseIMGCollectionCell *cell = (ChooseIMGCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.Img_view.frame=CGRectMake(5, 5, (RECRWITCH-60-20)/3 - 10, (RECRWITCH-60-20)/3 - 10);
    cell.SuperVC = self;
//    cell.Typelabel.frame=CGRectMake(5, 40, cell.Img_view.frame.size.width, 35);
    cell.Img_button.frame=CGRectMake((RECRWITCH-60-20)/3 - 5-17.5, 2.5, 22.5, 22.5);
    [cell.Img_button setBackgroundImage:[UIImage imageNamed:@"shanchu.png"]
                               forState:UIControlStateNormal];
    cell.Typelabel.hidden=YES;
    
    if (_Array.count>8) {
        NSDictionary *lin_dic = [_Array objectAtIndex:indexPath.row];
        UIImage *img=[lin_dic objectForKey:@"img"];
        cell.Img_view.image=img;
        cell.Img_button.hidden=NO;
    }else{
        if (indexPath.row==_Array.count) {
            cell.Img_view.image=[UIImage imageNamed:@"addfabu.png"];
            cell.Img_button.hidden=YES;
        }else{
            NSDictionary *lin_dic = [_Array objectAtIndex:indexPath.row];
            UIImage *img=[lin_dic objectForKey:@"img"];
            cell.Img_view.image=img;
            cell.Img_button.hidden=NO;
        }
    }
    cell.selectBlock = ^(BOOL chuanok) {
        [self.Array removeObjectAtIndex:indexPath.row];
        [self here_relaod];
    };
    return cell;
}

//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_Array.count>2) {
        [self show_img:indexPath.row];
    }else{
        if (indexPath.row==_Array.count) {
            [self ChangeLogo];
        }else{
            [self show_img:indexPath.row];
        }
    }
}

-(void)show_img:(NSInteger)no_type{
    
    NSDictionary *diclin = [_Array objectAtIndex:no_type];
    NSMutableArray *ling_img_array=[NSMutableArray new];
    for (NSDictionary *dic in _Array) {
        UIImage *img=[dic objectForKey:@"img"];
        [ling_img_array addObject:img];
    }
    
    XLPhotoBrowser *browser = [XLPhotoBrowser showPhotoBrowserWithImages:ling_img_array currentImageIndex:no_type];
    browser.seletBlock = ^(BOOL tui_ok) {
        
    };
}

//取消选择了某个cell
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
}

// cell点击变色
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
}

// cell点击变色
- (void)collectionView:(UICollectionView *)collectionView  didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
}



-(void)ChangeLogo{
    
    NSArray *linarray;
    
    linarray = [[NSArray alloc] initWithObjects:@"所有照片",@"相机",@"相册", nil];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle: UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [linarray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:obj style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            if ([obj isEqualToString:@"所有照片"]) {
                
                UIImagePickerController *imagepicker = [[UIImagePickerController alloc] init];
                imagepicker.delegate   = self;
                imagepicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                imagepicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                
                if(AppsystemVersion.doubleValue >= 12.0) {
                    
                    UIView *linview= [[UIView alloc] initWithFrame:CGRectMake(0, 0, RECRWITCH, NAV_Height-40)];
                    linview.backgroundColor=[UIColor whiteColor];
                    [imagepicker.view addSubview:linview];
                    
                    imagepicker.navigationBar.backgroundColor = [UIColor whiteColor];
                }
                
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagepicker animated:YES completion:NULL];
            }else if ([obj isEqualToString:@"相机"]){
                
                if (![self isFrontCameraAvailable]) {
                    [SVProgressHUD showErrorWithStatus:@"相机不可用"];
                    return ;
                }
                UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
                imagePicker.delegate = self;
                imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                
                [_SuperVC presentViewController:imagePicker animated:YES completion:NULL];
            }else if ([obj isEqualToString:@"相册"]){
                SGImagePickerController *picker = [[SGImagePickerController alloc] init];
                
                picker.maxCount = 3-self.Array.count;
                [picker setDidFinishSelectThumbnails:^(NSArray *thumbnails) {
                    
                }];
                [picker setDidFinishSelectImages:^(NSArray *images) {

                    for (UIImage *img in images) {
                        NSMutableDictionary *dic_lin=[NSMutableDictionary new];
                        [dic_lin setObject:img forKey:@"img"];
                        [self.Array addObject:dic_lin];
                    }
                    
                    [self here_relaod];
                }];
                
                if(AppsystemVersion.doubleValue >=12.0) {
                    
                    UIView *linview= [[UIView alloc] initWithFrame:CGRectMake(0, 0, RECRWITCH, NAV_Height-40)];
                    linview.backgroundColor=[UIColor whiteColor];
                    [picker.view addSubview:linview];
                    
                    picker.navigationBar.backgroundColor = [UIColor whiteColor];
                }
                
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:picker animated:YES completion:nil];
                
            }
            
        }];
        [alertController addAction:deleteAction];
    }];
    
    [alertController addAction:cancelAction];
    
    [_SuperVC presentViewController:alertController animated:YES completion:nil];
    
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *) info{
    
    UIImage *img;
    
    if(picker.sourceType==UIImagePickerControllerSourceTypeCamera){
        img=[info objectForKey:UIImagePickerControllerOriginalImage];
        UIImage *newImg=[self imageWithImageSimple:img scaledToSize:CGSizeMake(600, 600)];
        NSMutableDictionary *dic_lin=[NSMutableDictionary new];
        [dic_lin setObject:newImg forKey:@"img"];
        [_Array addObject:dic_lin];

        [_SuperVC dismissViewControllerAnimated:YES completion:nil];
        
        [self here_relaod];
        
    }else{
        img=[info objectForKey:UIImagePickerControllerOriginalImage];
        
        //先获取asset在ALAssetsLibrary库中的url
        NSURL *imageUrl = [info valueForKey:UIImagePickerControllerReferenceURL];
        
        ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
        [assetsLibrary assetForURL:imageUrl resultBlock:^(ALAsset *asset) {
            ALAssetRepresentation *representation = [asset defaultRepresentation];
            NSString *imageName = representation.filename;
            
            UIImage *newImg=[self imageWithImageSimple:img scaledToSize:CGSizeMake(600, 600)];
            NSMutableDictionary *dic_lin=[NSMutableDictionary new];
            [dic_lin setObject:newImg forKey:@"img"];
            [self.Array addObject:dic_lin];
            
            [[UIApplication sharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:YES completion:nil];
            
            [self here_relaod];
            
        } failureBlock:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"获取失败"];
            [[UIApplication sharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:YES completion:nil];
        }];
    }
}

-(void)Gif_url:(NSURL *)gifurl andShowimg:(UIImage *)lin_img{
    ALAssetsLibrary* assetLibrary = [[ALAssetsLibrary alloc] init];
    void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *) = ^(ALAsset *asset) {
        
        if (asset != nil) {
            
            ALAssetRepresentation *rep = [asset defaultRepresentation];
            Byte *imageBuffer = (Byte*)malloc(rep.size);
            NSUInteger bufferSize = [rep getBytes:imageBuffer fromOffset:0.0 length:rep.size error:nil];
            NSData *data = [NSData dataWithBytesNoCopy:imageBuffer length:bufferSize freeWhenDone:YES];
            
            NSMutableDictionary *dic_lin=[NSMutableDictionary new];
            [dic_lin setObject:lin_img forKey:@"img"];
            [self->_Array addObject:dic_lin];
            
            [_SuperVC dismissViewControllerAnimated:YES completion:nil];
            
            [self here_relaod];
            
        }else {
            [SVProgressHUD showErrorWithStatus:@"获取失败"];
            [_SuperVC dismissViewControllerAnimated:YES completion:nil];
        }
    };
    [assetLibrary assetForURL:gifurl
                  resultBlock:ALAssetsLibraryAssetForURLResultBlock
                 failureBlock:^(NSError *error){
                     [SVProgressHUD showErrorWithStatus:@"获取失败"];
                     [_SuperVC dismissViewControllerAnimated:YES completion:nil];
                 }];
}

-(UIImage *) imageWithImageSimple:(UIImage*) image scaledToSize:(CGSize) newSize{
    newSize.height=image.size.height*(newSize.width/image.size.width);
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  newImage;
}

-(void)here_relaod{
    
    [_collectionview reloadData];
    [self layoutIfNeeded];
    if (_Array.count>1) {
        [_collectionview scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_Array.count-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
}







#pragma mark - 摄像头和相册相关的公共类
// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

// 前面的摄像头是否可用
- (BOOL) isFrontCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

// 后面的摄像头是否可用
- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

@end
